package com.anhtuan.reminder.listelement;

import com.anhtuan.reminder.MainActivity;
import com.anhtuan.reminder.R;
import com.anhtuan.reminder.dialogs.DeleteWarningDialog;
import com.anhtuan.reminder.providers.TasksProviderWrapper;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;

public class ClearTaskListElement extends BaseListElement{

	
	public ClearTaskListElement(Activity activity, int requestCode) {
		super(activity, 
				activity.getResources().getDrawable(R.drawable.action_delete), 
				activity.getResources().getString(R.string.clear_all_text),
				activity.getResources().getString(R.string.clear_all_description),
				null,
				requestCode);
	}
	
	@Override
	public OnClickListener getOnClickListener() {
		
		return new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						ClearAllTask task = new ClearAllTask(getActivity());
						task.execute();
					}
				};
				
				DeleteWarningDialog dialog = new DeleteWarningDialog();
				dialog.setPositiveButtonOnClickListener(onClickListener);
				dialog.setNegativeButtonOnClickListener(null);
				dialog.show(((MainActivity)getActivity()).getSupportFragmentManager(), dialog.getTag());
			}
		};
	}
	
	@Override
	public void onActivityResult(Intent data) {
		// Nothing to do
	}
	
	private class ClearAllTask extends AsyncTask<Void, Void, Void> {

		private ProgressDialog progressDialog;
		
		public ClearAllTask(Context context) {
			progressDialog = new ProgressDialog(context);
		}
		
		@Override
		protected void onPreExecute() {
			progressDialog.setMessage(getActivity().getResources().getString(R.string.progress_dialog_deleting_text));
			progressDialog.show();
		}
		
		@Override
		protected void onPostExecute(Void result) {
			
			if (progressDialog.isShowing()) {
				
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				progressDialog.dismiss();
			}
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			TasksProviderWrapper.deleteAllRecord(ClearTaskListElement.this.getActivity().getContentResolver());
			publishProgress();
			return null;
		}
		
		@Override
		protected void onProgressUpdate(Void... values) {
			((MainActivity) getActivity()).stopScheduleAllTask();
			((MainActivity) getActivity()).removeAllTask();
		}
	}
}
